<template>
    <div>
        <el-page-header @back="goBack" :content="pageTitle"></el-page-header>
        <div class="common_line"></div>
        <el-form ref="addForm" :model="addForm" :rules="rules" label-width="auto" style="margin-top: 20px;width: 85%;">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="订单类型:" prop="record_type">
                        <el-select style="width: 240px;" v-model="addForm.record_type" @change="typeChange"
                            placeholder="请选择">
                            <el-option  label="销售单" :value="1"></el-option>
                            <el-option  label="退货单" :value="2"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="客户:" prop="customer">
                        <div class="choose_border" @click="chooseCustomers()">
                            <span style="color: #c0c4cf;" v-if="!customer_name">请选择</span>
                            <span>{{ customer_name }}</span>
                            <!-- <i class="el-icon-circle-close icon" @click.stop="clearValue('customer')"></i> -->
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="日期:" prop="orders_date">
                        <el-date-picker v-model="addForm.orders_date" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                            style="width: 240px" placeholder="请选择" clearable>
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="isAdmin">
                    <el-form-item label="经办人:">
                        <div class="choose_border" @click="chooseUsers('handler')">
                            <span style="color: #c0c4cf;" v-if="!handler_name">请选择</span>
                            <span>{{ handler_name }}</span>
                            <!-- <i class="el-icon-circle-close icon" @click.stop="clearValue('handler')"></i> -->
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-else>
                    <el-form-item label="经办人:">
                        <div>{{ handler_name }}</div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="22">
                    <el-form-item label="选择单据:">
                        <div @click="addOrder" class="add_order">添加单据</div>
                        <el-table :data="selectOrders" border style="width: 100%" :key="tableKey">
                            <el-table-column label="序号" align="center" width="60" prop="index" />
                            <el-table-column label="订单编号" align="center" prop="order_no" />
                            <!-- <el-table-column label="开单日期" align="center" prop="order_date" /> -->
                            <el-table-column v-if="addForm.record_type===1" label="未收款" align="center" prop="rightValue" />
                            <el-table-column v-if="addForm.record_type===1" label="本次收款" align="center" prop="cur_money" />
                            <el-table-column v-if="addForm.record_type===2" label="未退款" align="center" prop="rightValue" />
                            <el-table-column v-if="addForm.record_type===2" label="本次退款" align="center" prop="cur_money" />
                            <el-table-column label="操作" min-width="80" align="center" class-name="small-padding fixed-width">
                                <template slot-scope="scope">
                                    <el-button
                                        size="mini"
                                        type="text"
                                        @click="handleRemove(scope.row)"
                                        style="font-weight: bold;"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item :label="addForm.record_type===1?'本次收款金额:':'本次退款金额:'" prop="orders_fee">
                        <div v-if="selectOrders.length">{{ '￥'+addForm.orders_fee }}</div>
                        <el-input v-else style="width: 240px" v-model="addForm.orders_fee" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="结算账户:">
                        <el-select style="width: 240px;" v-model="addForm.pay_type" placeholder="请选择">
                            <el-option v-for="item in payTypes" :key="'pay_'+item.value" 
                                :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="22">
                    <el-form-item label="备注:">
                        <el-input maxlength="200" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" v-model="addForm.remark" placeholder="请输入" clearable />
                    </el-form-item>
                </el-col>
            </el-row>

            <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;margin-top: 10px;">上传附件</div>
            <el-row>
                <el-upload multiple ref="fileUpload" action="anything" :file-list="fileUploadList"
                    :http-request="(params) => uploadSectionFile(params)" :limit="5"
                    :on-preview="previewClick" :on-remove="(file) => removeFile(file)">
                    <el-button size="small" :disabled="canUpload" :class="canUpload?'btn_info_color':'btn_primary_color'" 
                        style="margin: 10px 0 0 40px;" icon="el-icon-upload2">上传附件</el-button>
                    <div slot="tip" class="el-upload__tip" style="margin-left: 20px;white-space:nowrap;display: inline-block;">
                        最多上传5个附件，单个附件大小限制在{{ max_file_size }}MB之内
                    </div>
                </el-upload>
            </el-row>
        </el-form>
        
        <bottom-btns
            Width="80%"
            MarginTop="30px"
            :buttons="buttonList"
            @superBtnClick="handleButtonClick"
        ></bottom-btns>

        <el-dialog title="选择单据" :visible.sync="showOrderLists" 
            :close-on-click-modal="false" width="60%" center append-to-body>
            <div class="order_lists">
                <el-table :data="orders" row-key="id" ref="dialogTable" border style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="订单编号" align="center" prop="order_no" />
                    <el-table-column label="开单日期" align="center" prop="order_date" />
                    <el-table-column label="订单金额" align="center" prop="orderPrice" />
                    <el-table-column v-if="addForm.record_type===1" label="未收款" align="center" prop="rightValue" />
                    <el-table-column v-if="addForm.record_type===1" label="本次收款" align="center">
                        <template slot-scope="scope">
                            <input class="inner_input" style="width: 70px;" v-model="scope.row.cur_money"
                                @blur="moneyBlur($event, scope.row)" placeholder="请输入">
                        </template>
                    </el-table-column>
                    <el-table-column v-if="addForm.record_type===2" label="未退款" align="center" prop="rightValue" />
                    <el-table-column v-if="addForm.record_type===2" label="本次退款" align="center">
                        <template slot-scope="scope">
                            <input class="inner_input" style="width: 70px;" v-model="scope.row.cur_money"
                                @blur="moneyBlur($event, scope.row)" placeholder="请输入">
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button class="btn_primary_color" @click="chooseOrdersOk">确 定</el-button>
                <el-button @click="closeDialog">取 消</el-button>
            </span>
        </el-dialog>

        <!-- 选择销售人员 -->
        <choose-user
            :showChooseUser="showChooseUserAlert"
            :selectUsers="selectedUsers.users"
            :title="selectedUsers.title"
            @chooseOK="chooseUserOK"
            @hidden="showChooseUserAlert=false"
        ></choose-user>

        <!-- 选择客户 -->
        <choose-customer
            :showChooseCustomer="showChooseCustomerAlert"
            :selectUsers="customerList"
            @chooseOK="chooseCustomerOK"
            @hidden="showChooseCustomerAlert=false"
        ></choose-customer>
    </div>
</template>

<script>
import { getUserList } from "@/api/user";
import { getCustomerList, addReceivePayment, editReceivePayment, getReceivePaymentInfo } from "@/api/cooperate";
import { getOrderList, listSaleReturns } from "@/api/order";
import bottomBtns from "@/components/bottomBtns";
import chooseUser from "@/components/chooseUser";
import chooseCustomer from "@/components/chooseCustomer";
import { baseUrl } from '@/config/env'
import { getToken } from '@/utils/auth'
const moment = require('moment')

export default {
    name: 'receiveOrderEdit',
    components: {
        bottomBtns,
        chooseUser,
        chooseCustomer,
    },
    data() {
        return {
            showLoading: false,
            showChooseUserAlert: false,
            showChooseCustomerAlert: false,
            userType: '',
            isAdmin: false,
            showOrderLists: false,
            canUpload: false,
            customerId: '',
            pageTitle: '',
            addForm: {
                corp: '',
                customer: '',
                handler_user: '',
                orders_date: '',
                orders_fee: '0.00',
                pay_type: 2,
                record_type: 1, //1收款--销售开单|2付款--销售退单
                remark: '',
                file_id_list: [],
                order_relations: []
            },
            rules:{
                orders_fee: [
                    { required: true, message: "请输入金额", trigger: "blur" },
                ],
                record_type: [
                    { required: true, message: "请选择类型", trigger: "change" },
                ],
                orders_date: [
                    { required: true, message: "请选择日期", trigger: "change" },
                ],
                customer: [
                    { required: true, message: "请选择客户", trigger: "change" },
                ],
            },
            customerList: [],
            customer_name: '',
            handlersList: [],
            handler_name: '',
            payTypes: [
                {label: '微信', value: 2},
				{label: '支付宝', value: 5},
				{label: '现金', value: 1},
				{label: '银行转账', value: 3},
				{label: '其他', value: 4}
            ],
            orders: [],
            chooseOrders: [],
            selectOrders: [],
            tableKey: 1,
            buttonList: [
                { name: '保存', type: 'commit', id:'1' },
                { name: '取消', type: 'cancel', id:'2' }
            ],
            fileUploadList: [],
            max_file_size: 10,  //最大可上传文件大小（MB）
        }
    },
    computed: {
        selectedUsers() {
            let users = []
            if (this.addForm.handler_user){
                users = [{id: this.addForm.handler_user}]
            }
            let title = '选择经办人'
            return {
                users, title
            }
        }
    },
    props: {
        corpId: {
            type: Number
        },
        editId: {
            type: Number
        },
        cusInfo: {
            type: [Object]
        }
    },
    watch: {
        selectOrders(value) {
            let totals = 0
            if (value.length) {
                value.forEach(item => {
                    totals = this.$common.plusFloat(totals, item.cur_money)
                })
            }
            this.addForm.orders_fee = totals
        }
    },
    mounted() {
        this.addForm.corp = this.corpId
        this.isAdmin = this.$store.state.isAdmin
        this.addForm.orders_date = moment().format('yyyy-MM-DD')
        this.handler_name = this.$store.state.userInfo.username
        this.addForm.handler_user = this.$store.state.userInfo.id
        if (this.editId) {
            this.pageTitle = '编辑收款单'
            this.getOrderInfo()
        }else{
            this.pageTitle = '新增收款单'
        }
        if (this.cusInfo && this.cusInfo.id){
            this.addForm.customer = this.cusInfo.id
            this.customer_name = decodeURIComponent(this.cusInfo.name)
        }
    },
    methods: {
        goBack() {
            this.$emit('hidden', '')
        },
        chooseUsers(type) {
            this.userType = type
            this.showChooseUserAlert = true
        },
        chooseCustomers() {
            this.showChooseCustomerAlert = true
        },
        clearValue(type) {
            if (type == 'customer'){
                this.addForm.customer = ''
                this.customer_name = ''
            }
        },
        chooseUserOK(res) {
            if (this.userType == 'handler'){
                this.addForm.handler_user = res.length ? res[0].id : ''
                this.handler_name = res.length ? res[0].username : ''
            }
            this.showChooseUserAlert = false
        },
        chooseCustomerOK(res) {
            this.addForm.customer = res.length ? res[0].id : ''
            this.customer_name = res.length ? res[0].name : ''
            this.showChooseCustomerAlert = false
        },
        typeChange() {
            this.selectOrders = []
        },
        // 获取详情
        getOrderInfo() {
            let _this = this
            getReceivePaymentInfo(this.editId, {corp: this.addForm.corp}).then(res => {
                let info = res.data.data
                _this.customer_name = info.customer_detail?info.customer_detail.customer_name:''
                _this.handler_name = info.handler_user_detail?info.handler_user_detail.username:''
                if (info.record_type === 1){
                    _this.selectOrders = info.order_relations_detail.filter((item, index) => {
                        item.index = index+1
                        item.order_no = item.related_order_no
                        item.rightValue = item.pending_payment||0
                        item.cur_money = item.orders_fee
                        item.id = item.related_order_id
                        return item
                    })
                }else{
                    _this.selectOrders = info.return_order_relations_detail.filter((item, index) => {
                        item.index = index+1
                        item.order_no = item.related_order_no
                        item.rightValue = item.pending_payment||0
                        item.cur_money = item.orders_fee
                        item.id = item.related_order_id
                        return item
                    })
                }
                _this.addForm = {
                    id: info.id,
                    corp: info.corp,
                    customer: info.customer_detail?info.customer_detail.customer_id:'',
                    handler_user: info.handler_user_detail?info.handler_user_detail.id:'',
                    orders_date: info.orders_date,
                    orders_fee: parseFloat(info.orders_fee),
                    pay_type: parseInt(info.pay_type),
                    record_type: info.record_type,
                    remark: info.remark,
                    order_relations: []
                }

                // 附件
                if (info.file_list_show && info.file_list_show.length){
                    _this.addForm.file_id_list = info.file_list_show.map(item => item.id)
                    _this.fileUploadList = info.file_list_show.filter(item => {
                        item.url = item.url_show
                        item.name = item.file_name
                        return item
                    })
                }else{
                    _this.addForm.file_id_list = []
                }
            })
        },
        addOrder() {
            if (!this.addForm.customer) {
                this.$message({
                    message: '请先选择客户',
                    type: 'error'
                })
                return
            }
            this.showOrderLists = true
            let that = this
            this.$nextTick(() => {
                that.loadTables()
            })
        },
        loadTables() {
            let that = this
            if (this.addForm.record_type === 1){
                getOrderList({
                    corp: this.addForm.corp,
                    is_draft: '0',
                    customer_id: this.addForm.customer,
                    is_pay: '0',
                    page: 1,
                    num: 999
                }).then(res => {
                    let lists = res.data.data.sale_order_list.filter(item => {
                        item.order_no = item.corp_order_no
                        item.order_date = item.sale_date
                        item.orderPrice = parseFloat(item.order_price)
                        item.rightValue = item.pending_payment?parseFloat(item.pending_payment):0
                        item.cur_money = item.rightValue  //本次收款
                        return item
                    })
                    that.orders = lists
                    that.$nextTick(() => {
                        that.selectOrders.forEach(item => {
                            const table = that.$refs.dialogTable;
                            if (table && table.toggleRowSelection) {
                                const rowToSelect = that.orders.find(order => order.id === item.id);
                                if (rowToSelect) {
                                    table.toggleRowSelection(rowToSelect, true);
                                }
                            }
                        })
                    })
                })
            }else{
                listSaleReturns({
                    corp: this.addForm.corp,
                    is_draft: '0',
                    customer_id: this.addForm.customer,
                    is_pay: '0',
                    page: 1,
                    num: 999
                }).then(res => {
                    let lists = res.data.data.sale_return_list.filter(item => {
                        item.order_no = item.corp_order_no
                        item.order_date = item.return_date
                        item.orderPrice = parseFloat(item.chargeback_price)
                        item.rightValue = item.pending_payment?parseFloat(item.pending_payment):0
                        item.cur_money = item.rightValue  //本次退款
                        return item
                    })
                    that.orders = lists
                    that.$nextTick(() => {
                        that.selectOrders.forEach(item => {
                            const table = that.$refs.dialogTable;
                            if (table && table.toggleRowSelection) {
                                const rowToSelect = that.orders.find(order => order.id === item.id);
                                if (rowToSelect) {
                                    table.toggleRowSelection(rowToSelect, true);
                                }
                            }
                        })
                    })
                })
            }
        },
        handleRemove(row) {
            function removeByIndexAndReindex(arr, indexToRemove) {
                // 使用 filter 方法过滤掉指定 index 的元素
                let newArray = arr.filter(item => item.index!== indexToRemove);
                // 遍历新数组，重新设置 index 属性
                for (let i = 0; i < newArray.length; i++) {
                    newArray[i].index = i + 1;
                }
                return newArray;
            }
            this.selectOrders = removeByIndexAndReindex(this.selectOrders, row.index)
        },
        chooseOrdersOk() {
            this.selectOrders = this.chooseOrders.filter((item, index) => {
                item.index = index+1
                return item
            })
            this.orders = []
            this.showOrderLists = false
        },
        closeDialog() {
            this.chooseOrders = []
            this.orders = []
            this.showOrderLists = false
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.chooseOrders = selection
        },
        moneyBlur(val, row) {
            let value = val.target.value
            value = value.replace(/^(?!-)([^-\d.])/g, ''); // 只允许负号、数字和小数点
            const parts = value.split('.');
            if (parts.length > 2) {
                value = parts[0] + '.' + parts.slice(1).join(''); // 只取第一个小数点之前的部分
            }
            
            value = value ? parseFloat(value) : 0
            if (value > row.rightValue){
                value = row.rightValue
            } 
            row.cur_money = value
            this.$set(this.orders, this.orders.indexOf(row), row); 
            this.tableKey++;
        },
        handleButtonClick(item) {
            switch (item.id) {
                case '1':   // 保存
                    this.commit()
                    break;
                case '2':   // 取消
                    this.goBack()
                    break;
            
                default:
                    break;
            }
        },
        commit() {
            var that = this
            that.$refs['addForm'].validate(valid => {
                if(!valid) return

                that.addForm.order_relations = []
				that.selectOrders.forEach(item => {
					that.addForm.order_relations.push({
						related_order_id: item.id,
						orders_fee: item.cur_money
					})
				})

                let temp = null
                if (that.editId) {
                    temp = editReceivePayment(that.editId, that.addForm)
                }else{
                    temp = addReceivePayment(that.addForm)
                }
                temp.then(res => {
                    if (res.code == 200){
                        let isShow = res.data.data.is_show
                        let msg = ''
						if (that.editId){
							msg = isShow?'修改成功':'修改成功，请等待审核员审核'
						}else{
							msg = isShow?'新增成功':'新增成功，请等待审核员审核'
						}
                        that.$message({
                            message: msg,
                            type: 'success'
                        })
                        that.$emit('success')
                    }
                })
            })
        },
        // 选择客户
        personChange(value) {
            let [ id, name ] = value.split('&&')
            this.addForm.customer = id
            this.customer_name = name
        },
        remoteMethodWithCustomer(query) {
            if (query !== '') {
                this.showLoading = true
                getCustomerList({
                    corp: this.addForm.corp,
                    category: '',
                    search: query
                }).then(res => {
                    this.showLoading = false
                    this.customerList = res.data.data.customer_list.filter(item => {
                        item.label = item.name
                        item.value = item.id+'&&'+item.name
                        if (item.category_detail && item.category_detail.name){
                            item.label += ('（'+item.category_detail.name+'）')
                        }
                        return item
                    });
                })
            } else {
                this.customerList = []
            }
        },
        // 选择经办人
        handlerPersonChange(value) {
            let [ id, username ] = value.split('&&')
            this.addForm.handler_user = id
            this.handler_name = username
        },
        remoteMethodWithHandler(query) {
            if (query !== '') {
                this.showLoading = true
                getUserList({
                    corp: this.addForm.corp,
                    username: query
                }).then(res => {
                    this.showLoading = false
                    this.handlersList = res.data.users.filter(item => {
                        item.label = item.username
                        item.value = item.id+'&&'+item.username
                        if (item.phone_no){
                            item.label += ('（'+item.phone_no+'）')
                        }
                        return item
                    });
                })
            } else {
                this.handlersList = []
            }
        },
        // ===================== 附件上传相关 ===========================
        // 上传前校验
        beforeUpload (file) {
            let isRightSize = file.size / 1024 / 1024 < this.max_file_size
            if (!isRightSize) {
                this.$message.error('文件大小超过' + this.max_file_size + 'MB')
            }
            // let fileArr = file.name.split('.')
            // let isAccept = new RegExp(this[uploadType].accept.join('|')).test('.' + fileArr[fileArr.length - 1])
            // if (!isAccept) {
            //     this.$message.error('请上传' + this[uploadType].accept.join(',') + '类型的文件')
            // }
            return isRightSize
        },
        // 自定义附件上传
        uploadSectionFile (params) {
            let _this = this
            if (!this.beforeUpload(params.file)) {
                params.onError()
                return
            }
            if (this.canUpload) return
             const loading = this.$loading({
                lock: true,
                text: '正在上传附件中，请稍后...'
            });
            _this.canUpload = true
            const formdata = new FormData()
            formdata.append('up_file', params.file)
            formdata.append('file_name', params.file.name)
            var xhr = new XMLHttpRequest();
            xhr.open("POST", baseUrl+'/upload_file/ali_oss_priv', true); //链接改成你项目中的
            xhr.setRequestHeader("TOKEN", getToken());  //令牌改成你项目中的
            xhr.setRequestHeader("CORP-ID", this.addForm.corp);  //令牌改成你项目中的
            xhr.send(formdata);
            xhr.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    var obj = JSON.parse(xhr.responseText); //返回值
                    _this.addForm.file_id_list.push(obj.data.id)
                    _this.fileUploadList.push({
                        name: obj.data.file_name,
                        url: obj.data.url_show,
                        id: obj.data.id
                    })
                    _this.$message.success('上传成功')
                    _this.canUpload = false
                    loading.close();
                }
            }
        },
        previewClick(file) {
            location.href = file.url
        },
        removeFile(file) {
            this.fileUploadList = this.fileUploadList.filter(item => item.id !== file.id)
            this.addForm.file_id_list = this.addForm.file_id_list.filter(item => item !== file.id)
        }
    }
}
</script>

<style lang="less" scoped>
    @import '../../../style/mixin.less';
    .add_order {
        cursor: pointer;
        font-size: 14px;
        padding-left: 10px;
        color: @blue;
    }
    .order_lists {
        padding: 0 10px;
        max-height: 400px;
        overflow-y: auto;
    }
    .inner_input {
        border: 1px solid #ddd;
        padding: 8px 5px;
    }
</style>
<style>
.el-upload-list__item {
    margin-left: 36px !important;
    width: calc(100% - 36px) !important;
}
</style>